﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Collections;
using System.Net.Sockets;
using System.Net;

namespace AlgoLogicMessengerCompetitor
{
    /// <summary>
    /// Interaction logic for LogIn.xaml
    /// </summary>
    public partial class LogIn : Page
    {
        Thread thread;
        bool IsThreadRunning = false;
        ReaderWriterLock rwl = new ReaderWriterLock();
        ArrayList userList = new ArrayList();

        //sockets
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        NetworkStream serverStream = default(NetworkStream);

        //display data string storage

        string massConvoReadData = null;
        ArrayList machineList = new ArrayList();

        private void MulticastListener()
        {
            recv("224.168.100.2", "1000");
        }

        void recv(string mcastGroup, string port)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, int.Parse(port));
            s.Bind(ipep);
            IPAddress ip = IPAddress.Parse(mcastGroup);
            s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));
            IsThreadRunning = true;
            while (IsThreadRunning)
            {
                byte[] b = new byte[500];
                s.Receive(b);
                string str = System.Text.Encoding.ASCII.GetString(b, 0, b.Length);
                str = str.Replace("\0", "");
                if (str.StartsWith("Hello"))
                {
                    string[] array = str.Split('#', '|', '\\');
                    if (array.Length > 1)
                    {
                        if (!userList.Contains(array[1].Substring(0, 5).ToString()))
                        {
                            //Get the machine name eg. IT786
                            userList.Add(array[1].Substring(0, 5));
                            machineList.Add(array[1].ToString());
                            UpdateComboBox();

                        }
                    }
                }
            }
        }

        public LogIn()
        {
            InitializeComponent();
            thread = new Thread(new ThreadStart(MulticastListener));
            thread.Start();
        }

        void UpdateComboBox()
        {
            if (this.Dispatcher.Thread == Thread.CurrentThread)
            {
                this.Dispatcher.BeginInvoke(new Action(UpdateComboBox));
            }
            else
            {
                //invoke thread
                this.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(
                        delegate()
                        {
                            //cbxIPaddress.Items.Clear();
                            //In WPF, there is no AddRange method for comboBox, so used ItemsSource
                            //labIPaddress.ItemsSource = userList.ToArray();
                            labIPaddress.Content = userList[0].ToString();              
                        }
                     )
                );
            }
        }

        //private void btnCfm_Click(object sender, RoutedEventArgs e)
        //{
            //try
            //{
            //    try
            //    {
            //        string hostname = "";
            //        if (labIPaddress.SelectedItem != null)
            //        {
            //            foreach (string machineName in machineList)
            //            {
            //                if (labIPaddress.SelectedItem.ToString() == machineName.Substring(0, 5))
            //                {
            //                    hostname = Dns.GetHostByName(machineName).AddressList[0].ToString();
            //                    clientSocket.Connect(hostname, 8888);
            //                    IP.Address = hostname;
            //                    IP.facilitatorCom = machineName;
            //                }
            //            }
            //        }
            //        else
            //        {
            //            MessageBox.Show("Please select one lab !");
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show("IP Address error", "Connection Error", MessageBoxButton.OK, MessageBoxImage.Error);
            //    }

            //serverStream = clientSocket.GetStream();
            //byte[] outStream = System.Text.Encoding.ASCII.GetBytes("" + "#");
            //serverStream.Write(outStream, 0, outStream.Length);
            //serverStream.Flush();

            //Thread ctThread = new Thread(CheckName);
            //ctThread.Start();

            //    lblTeamName.Visibility = Visibility.Visible;
            //    tbxTeamName.Visibility = Visibility.Visible;
            //    btnConnect.Visibility = Visibility.Visible;

            //    btnCfm.Visibility = Visibility.Hidden;

            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show("Server is not Connected! Please Try Again!", "Connection Error", MessageBoxButton.OK, MessageBoxImage.Error);
            //}
        //}
   
        private void CheckName()
        {
            while (true)
            {
                try
                {
                    int bufferSize = clientSocket.ReceiveBufferSize;
                    byte[] inStream = new byte[bufferSize];
                    serverStream.Read(inStream, 0, bufferSize);
                    string returndata = System.Text.Encoding.ASCII.GetString(inStream);

                    // check the return msg
                    string[] filterMsgType = returndata.Split('|');

                    if (filterMsgType[1].ToString() == "NameUsed!")
                    {
                        string name = filterMsgType[0].ToString();
                        if (name == IP.teamName)
                        {
                           MessageBox.Show(filterMsgType[0].ToString() + " is Existing, Please Enter a New Name!", "Notification", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                    }
                    else if (filterMsgType[1].ToString() == "TeamCreated!")
                    {
                        string name = filterMsgType[0].ToString();

                        if (name == IP.teamName)
                        {
                            //Navigate to another page
                            NavigateMethod();
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

        }

        private void NavigateMethod()
        {
            if (this.Dispatcher.Thread == Thread.CurrentThread)
            {
                this.Dispatcher.BeginInvoke(new Action(NavigateMethod));
            }
            else
            {
                //invoke thread
                this.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(
                        delegate()
                        {
                            //Navigate to another page
                            NavigationService.Navigate(new Uri("NavigationPage.xaml", UriKind.Relative));
                        }
                     )
                );
            }
        }

        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            //try
            //{
                string hostname = "";

                foreach (string machineName in machineList)
                {
                    hostname = Dns.GetHostByName(machineName).AddressList[0].ToString();
                    if (!clientSocket.Connected)
                    {
                        clientSocket.Connect(hostname, 8888);
                    }
                    IP.Address = hostname;
                    IP.facilitatorCom = machineName;
                 }
            //}
 
            //catch (Exception ex)
            //{
            //    MessageBox.Show("IP Address error", "Connection Error", MessageBoxButton.OK, MessageBoxImage.Error);
            //}

            serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes("" + "#");
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();

            Thread ctThread = new Thread(CheckName);
            ctThread.Start();

            if (tbxTeamName.Text.Trim() != "")
            {
                if (tbxTeamName.Text.Length <= 12)
                {
                    IP.teamName = tbxTeamName.Text.Trim();
                    //send name to server
                    string uniqueName = "@command|changeUName|" + tbxTeamName.Text.Trim() + "|";
                    byte[] outStream1 = System.Text.Encoding.ASCII.GetBytes(uniqueName + "#");

                    if (serverStream != null)
                    {
                        byte[] outStreamm = System.Text.Encoding.ASCII.GetBytes("" + "#");
                        serverStream.Write(outStream1, 0, outStream1.Length);
                        serverStream.Flush();
                        tbxTeamName.Clear();
                    }
                }
                else
                {
                    MessageBox.Show("Maximum 12 Characters are Allowed!", "Invaild Name", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                MessageBox.Show("Please Enter a Name!", "Invaild Name", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Page_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.F5)
            {
                e.Handled = true;
            }
        }

        private void tbxmsg_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                btnConnect_Click(this, new RoutedEventArgs());
            }
        }
    }
}